var province = require('../../province.js');


var app = getApp(),
  fn = app.fn;
var QQMapWX = require("../../utils/qqmap-wx-jssdk.js");
var qqmapsdk;
Page({
  data: {
    newShow: true,
    addId: '',
    consignee: '',
    addressName: '',
    latitude: '',
    longitude: '',
    addressPhone: '',
    addressDetailed: '',
    provinceId: '',
    cityId: '',
    cityId: '',
    areaId: '',
    addressInfo: '',
    postcodes: '000000',
    address: [],
    set_default :0,
    provinceArray: [],
    cityArray: [],
    countyArray: [],
    provinceIndex: '',
    cityIndex: '',
    countyIndex: '',
    provinceName: '',
    cityName: '',
    countyName: '',
    addType: 0,

    block: 0,
  },
  ProID: '',
  CityID: '',
  AreID: '',
  cityArrayDemo: [],
  countyArrayDemo: [],

  onLoad: function(options) {


    if (options.block != null) {
      this.setData({
        block: options.block,
      })

    }


    this.setData({
      uid: app.globalData.uid,
    })

    this.animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease'
    });


    // this.getprovinceData();


    this.setData({
      block: options.block,
    })
  },


  onPullDownRefresh: function() {

  },

  getprovinceData: function() {
    var provinceArrayDemo = []

    for (var i = 0; i < province.provinceArray.length; ++i) {
      var item = province.provinceArray[i]
      provinceArrayDemo.push(item.name)
    }
    this.setData({
      provinceArray: provinceArrayDemo
    })
  },


  getInitData: function() {
    var that = this;

    fn.apiData({
      url: 'myaddress.php',
      data: {
        user_id: app.globalData.uid,
      },
      success: function(res) {
        if (res.data.success) {
          that.setData({
            'address': res.data.result
          });

          wx.hideToast();
        }
      }
    });
  },


  bindSelect: function(e) {
    var that = this;

    var address = that.data.address;
    var aid = e.currentTarget.dataset.id;
    var block = that.data.block;

    if (block == 1) {

      for (var i = 0; i < address.length; i++) {
        var addInfo = address[i];
        if (addInfo.addId == aid) {

          var pagesLength = getCurrentPages().length;

          var frontPage = getCurrentPages()[pagesLength - 2];

          frontPage.addressBlock(addInfo);
        }
      }

      wx.navigateBack({
        delta: 1
      })
    }
  },


  defaultClick: function(e) {
    var that = this;
    that.setData({
      addId: e.currentTarget.dataset.id
    });

    fn.apiData({
      url: 'selectAddress.php',
      data: {
        uid: that.data.uid,
        addId: that.data.addId
      },
      success: function(res) {

        wx.showToast({
          title: res.data.error_msg,
          icon: 'success',
          duration: 1000
        })
        if (res.data.success) {
          that.setData({
            'address': []
          });
          that.getInitData();
        }
      }
    });
  },


  deleteClick: function(e) {
    var that = this;
    that.setData({
      addId: e.currentTarget.dataset.id
    });
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗?',
      success: function(res) {
        if (res.confirm) {

        }
      }
    })

  },

  deleteData: function(e) {
    var that = this;
    fn.apiData({
      url: 'deleteAddress.php',
      data: {
        uid: that.data.uid,
        addId: that.data.addId
      },
      success: function(res) {

        wx.showToast({
          title: res.data.error_msg,
          icon: 'success',
          duration: 2000
        })
        if (res.data.success) {
          that.setData({
            'address': []
          });
          that.getInitData();
        }
      }
    });
  },


  detailsClick: function(e) {

    var that = this;
    that.setData({
      'newShow': false,
      addId: e.currentTarget.dataset.id,
      addType: 1,
    });
    fn.apiData({
      url: 'addressDetail.php',
      data: {
        uid: that.data.uid,
        addId: that.data.addId
      },
      success: function(res) {
        if (res.data.success) {
          that.setData({

            addressName: res.data.result.name,
            addressPhone: res.data.result.tel,
            addressDetailed: res.data.result.address,
            provinceId: res.data.result.province,
            cityId: res.data.result.city,
            areaId: res.data.result.area,
            provinceName: res.data.result.provinceName,
            cityName: res.data.result.cityName,
            countyName: res.data.result.areaName,
            provinceIndex: '',
            cityIndex: '',
            countyIndex: '',
          });

          this.ProID = that.data.provinceId,
            this.CityID = that.data.cityId,
            this.AreID = that.data.areaId,


            wx.hideToast();

          var proIndex;
          for (var i = 0; i < province.provinceArray.length; ++i) {
            var item = province.provinceArray[i]
            if (item.ProID == that.data.provinceId) {
              proIndex = i;
              break
            }
          }

          this.cityArrayDemo = []

          for (var i = 0; i < province.cityArray.length; ++i) {
            var item = province.cityArray[i]
            if (item.ProID == that.data.provinceId) {
              this.cityArrayDemo.push(item.name)
            }
          }

          var citIndex;
          for (var i = 0; i < this.cityArrayDemo.length; ++i) {
            var item = this.cityArrayDemo[i]
            if (item == that.data.cityName) {
              citIndex = i;
              break
            }
          }

          this.countyArrayDemo = []
          for (var i = 0; i < province.countyArray.length; ++i) {
            var item = province.countyArray[i]
            if (item.CityID == that.data.cityId) {
              this.countyArrayDemo.push(item.DisName)
            }
          }

          var couIndex;
          for (var i = 0; i < this.countyArrayDemo.length; ++i) {
            var item = this.countyArrayDemo[i]
            if (item == that.data.countyName) {
              couIndex = i;
              break
            }
          }

          that.setData({
            provinceIndex: proIndex,
            cityIndex: citIndex,
            countyIndex: couIndex,
            cityArray: this.cityArrayDemo,
            countyArray: this.countyArrayDemo,
          });
        }
      }
    });

    this.animation.opacity(1).translateY(0).step();
  },

  newOpen2: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
        var REGION_PROVINCE = [];
        var addressBean = {
          REGION_PROVINCE: null,
          REGION_COUNTRY: null,
          REGION_CITY: null,
          ADDRESS: null
        };

        function regexAddressBean(address, addressBean) {
          regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
          var addxress = regex.exec(address);
          addressBean.REGION_CITY = addxress[1];
          addressBean.REGION_COUNTRY = addxress[2];
          addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";

        }
        if (!(REGION_PROVINCE = regex.exec(res.address))) {
          regex = /^(.*?(省|自治区))(.*?)$/;
          REGION_PROVINCE = regex.exec(res.address);
          addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
          regexAddressBean(REGION_PROVINCE[3], addressBean);
        } else {
          addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
          regexAddressBean(res.address, addressBean);
        }
        that.setData({
          ADDRESS_1_STR: addressBean.REGION_PROVINCE + " " +
            addressBean.REGION_CITY + "" +
            addressBean.REGION_COUNTRY
        });
        that.setData(addressBean);
      }
    })
  },

  newOpen: function() {

    var that = this;



    wx.chooseLocation({
      success: function(res) {







        var e = res.latitude,
          s = res.longitude,
          n = e + "," + s;
        qqmapsdk = new QQMapWX({
          key: 'XVZBZ-N4DK3-66C3A-3RJ2N-MH6JT-BUBGH'
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: e,
            longitude: s
          },
          coord_type: 1,
          success: function(t) {
            var e = t.result.ad_info.location;

            var ddsd = t.result.address_component;

            var newaddresss = "";






            newaddresss = ddsd.province + ddsd.city + ddsd.district + res.name;






            that.setData({
              'addressInfo': ddsd,
              addressName: newaddresss,
              latitude: res.latitude,
              longitude: res.longitude
            })


          }
        });



      },
      fail: function() {

      },
      complete: function() {

      }
    })


  },


  newClose: function() {

    this.animation.opacity(0).translateY(500).step();

    setTimeout(function() {

      this.setData({
        'newShow': true
      });
    }.bind(this), 300);
  },


  submitClick: function() {


    this.addClick();

  },


  editorClick: function() {
    var that = this;
    fn.apiData({
      url: 'eidtAddress.php',
      data: {

        city: that.data.addressInfo.city,
        district: that.data.addressInfo.district,
        province: that.data.addressInfo.province,
        uid: that.data.uid,
        addId: that.data.addId,
        name: that.data.addressName,
        tel: that.data.addressPhone,
        postCode: that.data.postcodes,
        province: that.data.provinceId,
        city: that.data.cityId,
        area: that.data.areaId,
        address: that.data.addressDetailed,
      },
      success: function(res) {

        wx.showToast({
          title: res.data.error_msg,
          icon: '',
          duration: 2000
        })

        if (res.data.success) {
          that.newClose();
          that.setData({
            'address': []
          });
          that.getInitData();
        }
      }
    });
  },

  defaultChange : function(e){ 
    if (e.detail.value){
      this.setData({
        set_default : 1
      })
    } else{
      this.setData({
        set_default: 0
      })
    }
  },
  addClick: function() {
    var that = this;

    if (that.data.ajxtrue) {

      fn.apiData({
        url: 'user.php',
        data: {
          location_status: '2',
          act: 'insert_address',
          city: that.data.addressInfo.city,
          area: that.data.addressInfo.district,
          province: that.data.addressInfo.province,
          user_id: app.globalData.uid,
          consignee: that.data.consignee,
          mobile: that.data.addressPhone,
          postCode: that.data.postcodes,
          province: that.data.provinceId,
          lng: that.data.longitude,
          lat: that.data.latitude,
          address: that.data.addressName,
          house_number: that.data.addressDetailed,
          default :that.data.set_default
        },
        success: function(res) {
           
          // wx.showToast({
          //   title: res.data.error_msg,
          //   icon: '',
          //   duration: 2000
          // })



          if (res.data.code == 0) {



            var block = that.data.block;

            if (block > 0) {

              var pagesLength = getCurrentPages().length;

              var frontPage = getCurrentPages()[pagesLength - 2];

              wx.navigateTo({
                url: '../firmOrder/firmOrder?id=' + block
              })


            } else {

              wx.showToast({
                title: '保存成功',
                icon: '',
                duration: 2000
              })

              wx.navigateTo({
                url: '../myaddress/myaddress'
              })
            }
          }
        }
      });

    } else {

      wx.showToast({
        title: '手机号有误',
        image: '/images/address_close.png',
        duration: 2000
      })



    }
  },



  bindName: function(e) {
    this.setData({
      consignee: e.detail.value
    })
  },

  bindPhone: function(e) {
    var phone = e.detail.value;






    if (isNaN(phone)) {

      this.setData({
        ajxtrue: false
      })



      wx.showToast({
        title: '手机号有误',
        icon: 'success',
        image: '/images/address_close.png',
        duration: 2000
      })


    } else {

      this.setData({
        ajxtrue: true
      })

      this.setData({
        addressPhone: e.detail.value
      })
    }




  },
  bindDetailed: function(e) {
    this.setData({
      addressDetailed: e.detail.value
    })
  },


  bindProvinceChange: function(e) {

    var name;
    for (var i = 0; i < province.provinceArray.length; ++i) {
      var item = province.provinceArray[i]
      if (i == e.detail.value) {
        this.ProID = item.ProID,
          name = item.name
        break
      }
    }
    this.cityArrayDemo = []

    for (var i = 0; i < province.cityArray.length; ++i) {
      var item = province.cityArray[i]
      if (item.ProID == this.ProID) {
        this.cityArrayDemo.push(item.name)
      }
    }

    if (this.data.provinceId != this.ProID) {

      this.setData({
        provinceId: this.ProID,
        provinceName: name,
        provinceIndex: e.detail.value,
        cityArray: this.cityArrayDemo,
        cityIndex: '',
        countyIndex: '',
        cityId: '',
        areaId: '',
        cityName: '',
        countyName: '',
      })
    } else {

      this.setData({
        provinceId: this.ProID,
        provinceName: name,
        provinceIndex: e.detail.value,
        cityArray: this.cityArrayDemo,
      })

    }
  },

  bindCityChange: function(e) {

    var name;
    for (var j = 0; j < province.cityArray.length; ++j) {
      var item = province.cityArray[j]
      if (item.name == this.data.cityArray[e.detail.value]) {
        this.CityID = item.CityID,
          name = item.name
        break
      }
    }

    this.countyArrayDemo = []
    for (var i = 0; i < province.countyArray.length; ++i) {
      var item = province.countyArray[i]
      if (item.CityID == this.CityID) {
        this.countyArrayDemo.push(item.DisName)
      }
    }

    if (this.data.cityId != this.CityID) {
      this.setData({
        cityId: this.CityID,
        cityIndex: e.detail.value,
        cityName: name,
        countyArray: this.countyArrayDemo,
        countyIndex: '',
        areaId: '',
        countyName: '',
      })

    } else {
      this.setData({
        cityId: this.CityID,
        cityIndex: e.detail.value,
        cityName: name,
        countyArray: this.countyArrayDemo,
      })

    }



  },

  bindCountyChange: function(e) {
    var name;

    for (var i = 0; i < province.countyArray.length; ++i) {
      var item = province.countyArray[i]
      if (item.DisName == this.data.countyArray[e.detail.value]) {
        this.AreID = item.Id,
          name = item.DisName
        break
      }
    }

    this.setData({
      areaId: this.AreID,
      countyIndex: e.detail.value,
      countyName: name,
    })
  },



  onReady: function() {

  },
  onShow: function() {

  },
  onHide: function() {

  },
  onUnload: function() {

  }
})